#include <QPainter>
#include <QPaintEvent>
#include <QImage>
#include "Tab.hpp"
#include "DrawManager.hpp"

Tab::Tab(Map *map):
    _tileImage(NULL),
    _map(map),
    _mousePressed(false)
{
    this->setMouseTracking(true);
    _time.start();
    _lastTime = _time.elapsed();
}

void    Tab::paintEvent(QPaintEvent *)
{
    QPainter    painter(this);
    int         drawAreaWidth = this->width();
    int         drawAreaHeight = this->height();

    DrawManager drawer(painter, drawAreaWidth, drawAreaHeight, _map->getWidth(), _map->getHeight());

    painter.drawPoint(0, 0);
    drawer.drawQuads(*_map);
    drawer.drawMap(*_map);
}

void    Tab::mousePressEvent(QMouseEvent* event)
{
    _mousePressed = true;
    if (_tileImage != NULL)
    {
        QPoint const&   pos = event->pos();
        addTile(pos.x(), pos.y());
    }
}

void    Tab::mouseReleaseEvent(QMouseEvent* event)
{
    _mousePressed = false;
}

void    Tab::mouseMoveEvent(QMouseEvent *event)
{
    QPoint const&   mousePos = event->pos();

    int             x = mousePos.x(), y = mousePos.y();

    // Add tile
    if (_tileImage != NULL && _mousePressed == true)
        addTile(x, y);

    // Map navigation
    int             mapWidth = _map->getWidth(), mapHeight = _map->getHeight();
    int             mapPositionX = _map->getPositionX(), mapPositionY = _map->getPositionY();
    int             currentTime = _time.elapsed();

    if (x < MOUSE_MOVE_INTERVAL && mapPositionX > 0 && currentTime - _lastTime > MOUSE_TIME_INTERVAL)
    {
        _map->setPositionX(mapPositionX - 1);
        this->update();
    }
    else if (x > this->width() - MOUSE_MOVE_INTERVAL && (mapWidth - mapPositionX) * TILE_SIZE > this->width() && currentTime - _lastTime > MOUSE_TIME_INTERVAL)
    {
        _map->setPositionX(mapPositionX + 1);
        this->update();
    }

    if (y < MOUSE_MOVE_INTERVAL && _map->getPositionY() > 0 && currentTime - _lastTime > MOUSE_TIME_INTERVAL)
    {
        _map->setPositionY(mapPositionY - 1);
        this->update();
    }
    else if (y > this->height() - MOUSE_MOVE_INTERVAL && (mapHeight - mapPositionY) * TILE_SIZE > this->height() && currentTime - _lastTime > MOUSE_TIME_INTERVAL)
    {
        _map->setPositionY(mapPositionY + 1);
        this->update();
    }
    _lastTime = currentTime;
}

void    Tab::addTile(int posX, int posY)
{
    posX = (posX / TILE_SIZE) + _map->getPositionX();
    posY = (posY / TILE_SIZE) + _map->getPositionY();
    if (posX < _map->getWidth() && posY < _map->getHeight())
    {
        Tile*   newTile = new Tile(_tileName, _tileImage, posX, posY);

        _map->addTile(newTile);
        this->update();
    }
}

void    Tab::setSelectedTile(QString const& name, QPixmap* tile)
{
    _tileName = name;
    _tileImage = tile;
}

Map&    Tab::getMap()
{
    return *_map;
}

